import { resolve } from 'node:path'
import { defineConfig, loadEnv } from 'vite'
import { createVitePlugins } from './src/config/plugins'
import { esbuildPluginMonacoEditorNls, Languages } from 'vite-plugin-monaco-editor-nls'
import zh_CN from './public/main.i18n.json'
import { createViteProxy } from './src/config/proxy'
import { serviceConfig } from './service.config'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  const env = loadEnv(mode, __dirname, '')
  const envConfig = serviceConfig[mode]

  return {
    base: env.VITE_BASE_URL,
    plugins: createVitePlugins(env),
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      host: true,
      port: 6060,
      proxy: env.VITE_HTTP_PROXY === 'Y' ? createViteProxy(envConfig) : undefined
    },
    build: {
      minify: 'esbuild',
      target: 'esnext',
      cssTarget: 'chrome80',
      rollupOptions: {
        // 关闭除屑优化，防止删除重要代码，导致打包后功能出现异常
        treeshake: false,
        output: {
          //静态资源分类打包
          chunkFileNames: 'static/js/[name]-[hash].js', // 引入文件名的名称
          entryFileNames: 'static/js/[name]-[hash].js', // 包的入口文件名称
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          // manualChunks配置 (依赖包从大到小排列)
          manualChunks: {
            // vue vue-router合并打包
            vue: ['vue', 'vue-router']
          }
        },
        plugins: [
          esbuildPluginMonacoEditorNls({
            locale: Languages.zh_hans,
            localeData: zh_CN.contents
          })
        ]
      },
      // 启用/禁用 gzip 压缩大小报告
      reportCompressedSize: false,
      // 提高超大静态资源警告大小
      chunkSizeWarningLimit: 2000
    },
    esbuild: {
      //清除全局的console.log和debug
      drop: mode === 'prod' ? ['console', 'debugger'] : []
    },
    // 汉化 monaco-editor
    optimizeDeps: {
      esbuildOptions: {
        plugins: [
          esbuildPluginMonacoEditorNls({
            locale: Languages.zh_hans,
            localeData: zh_CN.contents
          })
        ]
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern'
        }
      }
    }
  }
})
